package com.citywithincity.db;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.citywithincity.db.meta.TableStruct;

public class DbStatusUtil {
	
	private static final Map<String, DbStatus> MAP = new ConcurrentHashMap<String, DbStatus>();
	
	/**
	 * 注意tableName所指的表必须有一个主键
	 * @param tableName
	 * @param statusField
	 * @return
	 */
	public static DbStatus create(String tableName,String statusField){
		String key = tableName + statusField;
		DbStatus status = MAP.get(key);
		if(status == null){
			synchronized (MAP) {
				status = MAP.get(key);
				if(status == null){
					TableStruct tableStruct = Db.getStruct(0).getTableStruct(tableName);
					String pk=tableStruct.getPks()[0].getName();
					status = new DbStatusImpl(tableName, statusField,pk);
					MAP.put(key, status);
				}
			}
		}
		return status;
	}
	
	/**
	 * 
	 * @param tableName
	 * @param statusField
	 * @param pk					
	 * @return
	 */
	public static DbStatus create(String tableName,String statusField,String pk){
		String key = tableName + statusField + pk;
		DbStatus status = MAP.get(key);
		if(status == null){
			synchronized (MAP) {
				status = MAP.get(key);
				if(status == null){
					status = new DbStatusImpl(tableName, statusField,pk);
					MAP.put(key, status);
				}
			}
		}
		return status;
	}
	static class DbStatusImpl implements DbStatus{
		
		private String tableName;
		private String pk;
		private String statusField;
		
		public DbStatusImpl(String tableName,String statusField,String pk) {
			
			this.tableName = tableName;
			this.pk = pk;
			this.statusField = statusField;
		}

		@Override
		public boolean lockStatus(Object id, int oldStatus, int newStatus) {
			return Db.ar()
					.where(pk,id).where(statusField,oldStatus)
					.set(statusField,newStatus)
					.update(tableName) > 0;
		}

		@Override
		public void updateStatus(Object id, int newStatus) {
			Db.ar().where(pk,id).set(statusField,newStatus).update(tableName);
		}
		
		@Override
		public boolean lockStatus(Object id, int oldStatus, int newStatus, Map<String, Object> data) {
			return Db.ar()
					.where(pk,id).where(statusField,oldStatus)
					.set(statusField,newStatus)
					.set(data)
					.update(tableName) > 0;
		}

		@Override
		public void updateStatus(Object id, int newStatus, Map<String, Object> data) {
			Db.ar().where(pk,id).set(statusField,newStatus).set(data).update(tableName);
		}
		
		
		
	}
	
}
